# import the necessary packages
from skimage.filters import threshold_local
import argparse
import cv2 as cv

# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="The path to Image")
args = vars(ap.parse_args())

# load the image,convert it to grayscale,and blur it slightly
image = cv.imread(args["image"])
image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
blurred = cv.GaussianBlur(image, (5, 5), 0)
cv.imshow("Image", image)

# instead of manually specifying the threshold value,we can use adpative
# thresholding to examine neihgborhoods of pixels and adaptively threshold
# each neighborhood -- in this example,we'll calculate the mean value
# of the neighborhood area of 25 pixels and threshold based on that value;
# finnaly, our constrant C is substracted from the mean calculation (in this
# case 15)
thresh = cv.adaptiveThreshold(blurred, 255,
                              cv.ADAPTIVE_THRESH_MEAN_C, cv.THRESH_BINARY_INV, 25, 15)
cv.imshow("Opencv Mean Thresh", thresh)

# personally,I prefer the scikit-image adpative thresholding ,it just
# feels a lot more `Pythonic`
T = threshold_local(blurred, 29, offset=5, method="gaussian")
thres = (blurred < T).astype("uint8") * 255
cv.imshow("scikit-image Mean Thresh", thresh)
cv.waitKey(0)
